<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 文旅打卡模型
 * Class ArticleTypeModel
 * @package app\common\model
 */
class Scenic extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'scenic';

    /**
     * 关联新闻类型
     */
    public function conType()
    {
        return $this->hasOne(ScenicType::class, 'id', 'type_id');
    }


    
    /**
     * 列表
     * @param keywords string 搜索关键词(景点名称)
     * @param type_id int 类型id
     * @param is_play int 是否发布 1是 2否
     */
    public function lists($keywords = null, $type_id = null, $is_play = null, $limit = 10)
    {
        $res = $this->select('id', 'type_id', 'img', 'title', 'province', 'city', 'district', 'address', 'start_time', 'end_time', 'create_time', 'is_reader', 'is_play')
            ->with(["conType"=> function($query){
                $query->where('is_del' , 1);
            }])
            ->where(function ($query) use ($keywords, $type_id, $is_play) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
                if ($type_id) {
                    $type_id = !is_array($type_id) ? explode(',', $type_id) : $type_id;
                    $query->whereIn('type_id', $type_id);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
          //  ->where('t.is_del', 1)
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }



    /**
     * 列表
     * @param keywords string 搜索关键词(景点名称)
     * @param type_id int 类型id
     * @param is_play int 是否发布 1是 2否
     */
    public function listsByLonLat($keywords = null, $type_id = null, $is_play = null, $lon = null, $lat = null, $limit = 10)
    {
        $res = $this->select(
                'id',
                'type_id',
                'img',
                'title',
                'province',
                'city',
                'district',
                'address',
                'start_time',
                'end_time',
                'create_time',
                'is_reader',
                'is_play',
                'lon',
                'lat',
                DB::raw("round((2 * 6378.137 * ASIN(SQRT(POW( SIN( PI()*( $lat- lat )/ 360 ), 2 )+ COS( PI()* $lat / 180 )* COS( lat * PI()/ 180 )* POW( SIN( PI()*( $lon- lon )/ 360 ), 2 )))) * 1000) as distance")
            )
            ->with(["conType"=> function($query){
                $query->where('is_del' , 1);
            }])
            ->where(function ($query) use ($keywords, $type_id, $is_play) {
                if ($keywords) {
                    $query->where('title', 'like', "%$keywords%");
                }
                if ($type_id) {
                    $query->where('type_id', $type_id);
                }
                if ($is_play) {
                    $query->where('is_play', $is_play);
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('distance')
            ->paginate($limit)
            ->toArray();

        if (empty($res)) return false;

        foreach ($res['data'] as $key => $val) {
            $distance = m_switch_km($val['distance']);
            $res['data'][$key]['distance_old']  = $val['distance'];//返回原数据，比较用
            $res['data'][$key]['distance']  = sprintf("%.2f", $distance['num']);
            $res['data'][$key]['symbol']    = $distance['symbol'];
            $res['data'][$key]['type_name']    = !empty($val['con_type']) ? $val['con_type']['type_name'] : '';
            unset($res['data'][$key]['con_type']);
        }

        return $res;
    }



    /**
     * 详情
     * @param id 景点打卡id
     */
    public function detail($id)
    {
        $res = $this->select('id', 'type_id', 'img', 'title', 'province', 'city', 'district', 'address', 'start_time', 'end_time', 'create_time', 'is_reader', 'is_play','intro', 'lon', 'lat')
            ->with(["conType"=> function($query){
                $query->where('is_del' , 1);
            }])
            ->where('id', $id)
            ->where('is_del' , 1)
            ->first();

        return $res;
    }



    public function getNotLookNum()
    {
        $scenic_works_model = new ScenicWorks();
        $num = $scenic_works_model->where('scenic_id', $this->id)->where('is_look', 2)->count();
        return $num;
    }

    /**
     * 判断某个活动是否有人报名
     */
    public function scenicIsClock($id)
    {
        $apply_status = ScenicWorks::where('scenic_id', $id)->whereRaw("status = 1 || status = 2")->first();
        return $apply_status ? true : false;
    }

    /**
     * 获取景点打卡人数
     */
    public function getSignUserNum()
    {
        $scenic_works_model = new ScenicWorks();

        $num = $scenic_works_model->where('scenic_id', $this->id)->where('status', 2)->groupBy('user_id')->count();

        return $num;
    }

    /**
     * 获取景点热门评价
     */
    public function getScenicCommit()
    {
        $scenic_works_model = new ScenicWorks();

        $res = $scenic_works_model->where('scenic_id', $this->id)->where('status', 2)->orderByDesc('vote_num')->limit(2)->get();

        $commit = [];

        foreach ($res as $key => $value) {
            $commit[] = $value->title;
        }

        return $commit;
    }

    /**
     * 获取图片
     */
    public function getCoverImg()
    {
        $scenic_works_model = new ScenicWorks();

        $res = $scenic_works_model
            ->from($scenic_works_model . ' as w')
            ->join("scenic_works_img as i", 'w.id", "=", "i.scenic_word_id')
            ->where('scenic_id', $this->id)
            ->where('status', 2)
            ->orderByDesc('vote_num')
            ->limit(3)
            ->get();

        $img = [];

        if ($res->isEmpty()) {
            return [];
        } else {
            foreach ($res as $key => $value) {
                $img[] = $value['img'];
            }
        }

        return $img;
    }
}
